--*----------------------------------------------------------------------------
--
-- SplitString
--
--*----------------------------------------------------------------------------
IF EXISTS (
  SELECT 1
    FROM sys.objects
   WHERE type = 'TF'
     AND schema_id = SCHEMA_ID('dbo')
     AND name = 'SplitString'
)
DROP FUNCTION SplitString
GO
--*----------------------------------------------------------------------------
CREATE FUNCTION dbo.SplitString
(
  @String NVARCHAR(MAX)
, @SplitOn CHAR
)
RETURNS @RtnValue TABLE
(
  value NVARCHAR(MAX)
)
AS
BEGIN
  DECLARE @Count INT

  SET @Count = 1

  WHILE (CHARINDEX(@SplitOn, @String)>0)
  BEGIN
    INSERT INTO @RtnValue (value)
    SELECT LTRIM(RTRIM(SUBSTRING(@String, 1, CHARINDEX(@SplitOn, @String)-1)))

    SET @String = SUBSTRING(@String,CHARINDEX(@SplitOn,@String)+1,LEN(@String))
    SET @Count = @Count + 1
  END

  INSERT INTO @RtnValue (value)
  SELECT LTRIM(RTRIM(@String));

  RETURN
END
GO
